/**
 * Copyright (c) 2011 ~ 2015 Deepin, Inc.
 *               2013 ~ 2015 jouyouyun
 *
 * Author:      jouyouyun <jouyouwen717@gmail.com>
 * Maintainer:  jouyouyun <jouyouwen717@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 **/

package shortcuts

import (
	"pkg.linuxdeepin.com/lib/gio-2.0"
	dutils "pkg.linuxdeepin.com/lib/utils"
)

func ListCustomShortcuts() Shortcuts {
	var list Shortcuts
	for _, id := range getCustomIdList() {
		tmp := newCustomShortcut(id)
		if tmp == nil {
			continue
		}

		list = append(list, tmp)
	}

	return list
}

func AddCustomShortcut(name, action string, ss []string) string {
	id := dutils.GenUuid()
	gs := newCustomGSetting(id)
	defer gs.Unref()

	gs.Setting.SetString(gsKeyTempName, name)
	gs.Setting.SetString(gsKeyTempAction, action)
	gs.Setting.SetStrv(gsKeyTempShortcuts, ss)

	gio.SettingsSync()
	handleCustomAdded(id)

	return id
}

func DeleteCustomShortcut(id string) {
	gs := newCustomGSetting(id)
	defer gs.Unref()

	gs.Setting.Reset(gsKeyTempName)
	gs.Setting.Reset(gsKeyTempAction)
	gs.Setting.Reset(gsKeyTempShortcuts)

	gio.SettingsSync()
	handleCustomDeleted(id)
}

func newCustomShortcut(id string) *Shortcut {
	gs := newCustomGSetting(id)
	if gs == nil {
		return nil
	}

	return &Shortcut{
		Id:     id,
		Type:   KeyTypeCustom,
		Name:   gs.Setting.GetString(gsKeyTempName),
		Accels: gs.Setting.GetStrv(gsKeyTempShortcuts),
	}
}

func getCustomAction(id string) string {
	gs := newCustomGSetting(id)
	if gs == nil {
		return ""
	}
	defer gs.Unref()

	return gs.Setting.GetString(gsKeyTempAction)
}

func handleCustomAdded(id string) {
	gs := newKeybindGSetting()
	defer gs.Unref()
	list := gs.Setting.GetStrv(gsKeyCustomIdList)

	var found bool
	for _, v := range list {
		if v == id {
			found = true
			break
		}
	}

	if found {
		return
	}

	list = append(list, id)
	gs.Setting.SetStrv(gsKeyCustomIdList, list)
}

func handleCustomDeleted(id string) {
	gs := newKeybindGSetting()
	defer gs.Unref()
	list := gs.Setting.GetStrv(gsKeyCustomIdList)

	var (
		found   bool
		newList []string
	)
	for _, v := range list {
		if v == id {
			found = true
			continue
		}

		newList = append(newList, v)
	}

	if !found {
		return
	}

	gs.Setting.SetStrv(gsKeyCustomIdList, newList)
}

func getCustomIdList() []string {
	gs := newKeybindGSetting()
	defer gs.Unref()

	return gs.Setting.GetStrv(gsKeyCustomIdList)
}
